<?php

namespace addons\facrm\controller\facrm\clues;

use addons\facrm\library\BackendApi;
use think\Db;
use think\Exception;
use think\exception\PDOException;


/**
 * 线索跟进记录
 */
class Record extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'content';
    protected $childrenAdminIds = [];
    private $types = "clues";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Record');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 跟进记录
     */
    public function index($clues_id = null)
    {
		
		$clues_id=$this->request->request('clues_id','','intval');
        //设置过滤方法
        $this->request->filter(['strip_tags']);


        $filter_w = [];
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }


        $filter_w['types'] = $this->types;
        if ($clues_id) {
            $filter_w['types_id'] = $clues_id;
        }else{
            //全部
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            if ($this->childrenAdminIds)
                $filter_w['create_user_id'] = ['in', $this->childrenAdminIds];
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->order($sort, $order)->fetchSql(false)
            ->count();
        $list = $this->model
            ->where($filter_w)
            ->where($where)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
                'files' => function ($files) {
                    $files->field('id,url,record_id');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $lists = array();
        foreach ($list as $row) {
            $record_type_text = $row->record_type_text;
            $lists[] = array_merge($row->toArray(), ['record_type_text' => $record_type_text]);//获取器失效
        }
        $result = array("total" => $total, "rows" => $lists);
        $this->success('',$result);

    }

    /**
     * 添加跟进
     * @return mixed
     */
    public function add()
    {
		$ids=$this->request->request('ids','','intval');
		
		
        $clues = model('\app\admin\model\facrm\Clues');
        $row = $clues->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkCluesAuth($ids, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        $status_row = \app\admin\model\facrm\Fields::get(['source' => 'clues', 'name' => 'follow_status','status'=>'normal']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['next_time'] = $params['next_time'] ? strtotime($params['next_time']) : 0;
            $status_txt = "";
            if ($status_row && isset($status_row['content_list'][$params['follow_status']])) {
                $status_txt = $status_row['content_list'][$params['follow_status']];
                $params['content'] = "【{$status_txt}】" . $params['content'];
            }

            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'types_id' => $row->id,
                'types' => $this->types,
            ]);
            $result = $this->model->allowField(true)->validate('\app\admin\validate\facrm\Record.add')->save($params);
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error( $this->model->getError());
            }

            //更新客户表
            $row->next_time = $params['next_time'];
            $row->follow_time = time();
            $status_txt ? $row->follow_status = $params['follow_status'] : '';
            $row->save();

            //如果存在附件
            if ($params['image']) {
                $images = explode(",", $params['image']);
                $files_data = array();
                foreach ($images as $key => $v) {
                    $files_data[$key]['url'] = $v;
                    $files_data[$key]['types_id'] = $row->id;
                    $files_data[$key]['types'] = $this->types;
                }
                $this->model->files()->saveAll($files_data);
            }
            return $this->success(__('跟进成功'));
        }
        $row['follow_status_list']=$status_row?$status_row['content_list']:[];
        return $this->success('',$row);
    }

    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
		$ids=$this->request->request('ids','');
		
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }


            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->where('create_user_id', 'in', $this->childrenAdminIds)->select();


            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     *附件查看
     */
    public function files($ids = "")
    {
		$ids=$this->request->request('ids','','intval');
        //判断是否有权限
        $auth = new \addons\facrm\library\Auth();

        $clues_id = $this->request->param("clues_id");
        $filter_w['types'] = $this->types;
        if (!$clues_id) {
            $this->error(__('线索不存在'));
        }
        $filter_w['types_id'] = $clues_id;
        if (!$auth->checkCluesAuth($clues_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }

        $this->model = model('\app\admin\model\facrm\record\Files');
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->order($sort, $order)->fetchSql(false)
            ->count();
        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
        foreach ($list as $k => &$v) {
            $v['fullurl'] = cdnurl($v['url']);
            $v['imagetype'] = pathinfo($v['url'], PATHINFO_EXTENSION);
        }
        unset($v);
        $result = array("total" => $total, "rows" => $list);
        $this->success('',$result);

    }

}


